import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Demo2 {
    public static void main(String[] args) throws SQLException {
        //1、创建DataSourse
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/xmy4?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("5028");
        //2、建立连接
        Connection connection = dataSource.getConnection();
        //3、创建sql语句
       // String sql = "select * from student";
        String sql = "select * from student where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,3);
        //4、执行sql
       ResultSet resultSet = statement.executeQuery();//返回结果集合(临时表)
        //5、遍历结果集合
        //通过next方法可以获取到临时表中的每一行数据，如果获取到最后一行之后，再执行next返回false，循环结束
        while(resultSet.next()){
            //针对这一行进行处理
            //取出列的数据
           int id = resultSet.getInt("id");
           String name = resultSet.getString("name");
            System.out.println("id:"+id+" name:"+name);
        }
        //6、释放资源
        resultSet.close();
        statement.close();
        connection.close();
    }
}